package web.servlet;

import com.alibaba.fastjson.JSON;
import domain.Account;
import domain.Cart;
import domain.CartItem;
import service.CartService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class UpdateCartServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        Iterator<CartItem> cartItems = cart.getAllCartItems();
        CartService cartService = new CartService();
        Account account = (Account) session.getAttribute("loginAccount");

        Map<String, String> responseMap = new HashMap<>();
        //12.31改
        String itemIdJS = req.getParameter("itemId");  // 从JS传递的itemId
        String quantityString = req.getParameter("quantity"); // 从JS传递的quantity
        int quantity = Integer.parseInt(quantityString);

        //旧版
        while (cartItems.hasNext()) {
            CartItem cartItem = (CartItem) cartItems.next();
            //12.31改，先注释String itemId = req.getParameter("itemId");  // 从JS传递的itemId
            //System.out.println(itemId);
            String itemId = cartItem.getItem().getItemId();//获取的itemId！！！
            try {
                //12.31改：加了if判断
                if(itemId.equals(itemIdJS))
                {
                    if (quantity < 1)
                    {
                    cartItems.remove();
                    }
                    cart.setQuantityByItemId(itemId, quantity);
                    BigDecimal newTotal=cartItem.getTotal();
                    String newTotalString=newTotal.toString();
                    responseMap.put("newTotal", newTotalString);
                }
                //旧版开始
//                String quantityString = req.getParameter("quantity"); // 从JS传递的quantity
//                int quantity = Integer.parseInt(quantityString);
//                //System.out.println(quantity);
//                cart.setQuantityByItemId(itemId, quantity);
//                //System.out.println(itemId+cartItem.getTotal());
//                BigDecimal newTotal=cartItem.getTotal();
//                String newTotalString=newTotal.toString();
//                responseMap.put("newTotal", newTotalString);
                //旧版结束
                if (account != null) {
                    cartService.updateCart(account.getUsername(), itemId, quantity);
                }
                  //旧
//                if (quantity < 1) {
//                    cartItems.remove();
//                }
                //旧
            } catch (Exception e) {
                e.printStackTrace();  // 打印异常到控制台
                responseMap.put("error", "Error updating cart item");
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                PrintWriter out = resp.getWriter();
                out.print(JSON.toJSONString(responseMap));
                return;
            }
        }

        BigDecimal subTotal = cart.getSubTotal();
        String subTotalString = subTotal.toString();
        responseMap.put("subTotal", subTotalString);
        resp.setContentType("application/json");
        PrintWriter out=resp.getWriter();
        String jsonResponse = JSON.toJSONString(responseMap);
        System.out.println(jsonResponse);
        out.print(jsonResponse);
        //out.print(subTotalString);

    }
}